<template>
  <a-modal v-model:visible="visible" :title="title" width="calc(100% - 20px)" :mask-closable="true" @ok="save">
    <a-tree ref="treeRef" v-model:checked-keys="menuIds" size="mini" checkable :data="treeData" :field-names="{
      key: 'menuId', title: 'title',
      children: 'children'
    }"></a-tree>
  </a-modal>
</template>
<script lang="ts" setup>
import type { MenuOptionsItem } from '@/apis/system/menu'
import { Message } from '@arco-design/web-vue'
import { getMenuOptions, saveMenuOptions } from "@/apis/system/menu"
import { getRoleMenuIds } from '@/apis/system/role'

const roleId = ref<number | undefined>(undefined)

const treeData = ref<MenuOptionsItem[]>([])
const getTreeData = async () => {
  const res = await getMenuOptions()
  treeData.value = res.data

}

const title = computed(() => `分配权限`)
const visible = ref(false)
const menuIds = ref<Number[]>([])
const open = (data: { roleId: number, title: string }) => {
  roleId.value = data.roleId as number
  getTreeData()

  menuIds.value = []
  visible.value = true
  getRoleMenuIds({ roleId: data.roleId }).then((res) => {
    if (res.data) {
      menuIds.value = res.data.map(menuId => Number(menuId))

    } else {
      menuIds.value = []
    }

  })
}

const save = async () => {
  await saveMenuOptions({ menuIds: menuIds.value, roleId: roleId.value })
  Message.success('保存成功')
}

defineExpose({ open })
</script>

<style lang="scss" scoped></style>
